import axios from "axios";
import {useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
// 创建一个axios实例
const request = axios.create({
  baseURL: 'http://175.178.210.43:82/api',
  withCredentials: false, // 当跨域请求时发送cookie
  timeout: 0// 请求超时时间,5000(单位毫秒) / 0 不做限制
});

request.interceptors.request.use(
  config => {
    const accessToken = localStorage.getItem('accessToken')
    if(config.url!=='/admin/login'&&accessToken){
      config.headers.Authorization = `Bearer ${accessToken}`
    }
    return config
  },
  err=>{
    return Promise.reject(err);
  }
)

request.interceptors.response.use(
  response=>{
    return response
  },
  async error=>{
    const originalRequest = error.config;
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      try {
        // 使用 Refresh Token 刷新 Access Token
        const refreshToken = localStorage.getItem('refreshToken');
        if (!refreshToken) {
          throw new Error('未找到 Refresh Token');
        }

        const response = await axios.post('http://175.178.210.43:82/api/admin/refresh-token', {
          refreshToken,
        });

        const newAccessToken = response.data.data.accessToken;
        localStorage.setItem('accessToken',newAccessToken); // 存储新的 Access Token

        // 使用新的 Access Token 重试原始请求
        originalRequest.headers['Authorization'] = `Bearer ${newAccessToken}`;
        return request(originalRequest);
      } catch (refreshError) {
        console.error('刷新 Token 失败:', refreshError);
        // 刷新 Token 失败，跳转到登录页面
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        const router = useRouter()
        ElMessage.error('登录过期，请重新登录')
        router.replace({name:'Login'})
        return Promise.reject(refreshError);
      }
    }

    return Promise.reject(error);
  }
)

export default request;
